package com.github.admin.edu.security.jwt.server.service.impl;

import com.github.admin.edu.assembly.common.entity.JsonEntity;
import com.github.admin.edu.assembly.common.util.JsonUtils;
import com.github.admin.edu.assembly.string.util.StringUtils;
import com.github.admin.edu.oauth.server.api.entity.TokenEntity;
import com.github.admin.edu.security.jwt.common.service.JWTInfo;
import com.github.admin.edu.security.jwt.common.service.JWTInformation;
import com.github.admin.edu.security.jwt.common.service.RsaKeyHelper;
import com.github.admin.edu.security.jwt.common.util.JWTUtil;
import com.github.admin.edu.security.jwt.server.domain.JWTSysOauthManageDomain;
import com.github.admin.edu.security.jwt.server.entity.TSysOauthManage;
import com.github.admin.edu.security.jwt.server.service.ServerTokenManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.List;

/**
 * Create by IntelliJ IDEA
 * 用户：王建
 * 日期：2018-7-19
 */
@Service
public class ServerTokenManagerServiceImpl implements ServerTokenManagerService {


    @Autowired
    JWTSysOauthManageDomain domain;

    /**
     *
     * @param clientId 客户端编号（唯一）
     * @return
     */
    @Cacheable(value = "client_token",key = "#clientId")
    @Override
    public String getServiceToken(String clientId) {
        if(StringUtils.isNotBlank(clientId)){
            List<TSysOauthManage> list=domain.getAllByCode(clientId);
            if(null!=list&&list.size()>0){
                TSysOauthManage sysOauthManage=list.get(0);
                JWTInfo jwtInfo=new JWTInfo(sysOauthManage.getCode(),sysOauthManage.getName());
                try {
                    byte[] pri=RsaKeyHelper.generatePrivateKey(sysOauthManage.getPassword());
                    String token=JWTUtil.generateToken(jwtInfo,pri,100);
                    TokenEntity tokenEntity=new TokenEntity();
                    tokenEntity.setToken(token);
                    tokenEntity.setTime(100);
                    JsonEntity<TokenEntity> jsonEntity=new JsonEntity<>();
                    jsonEntity.setData(tokenEntity);
                    return JsonUtils.toJson(jsonEntity);
                } catch (IOException e) {
                    return JsonUtils.toJson(new JsonEntity<TokenEntity>(e.getMessage()));
                } catch (NoSuchAlgorithmException e) {
                    return JsonUtils.toJson(new JsonEntity<TokenEntity>(e.getMessage()));
                } catch (Exception e) {
                    return JsonUtils.toJson(new JsonEntity<TokenEntity>(e.getMessage()));
                }
            }
        }
        return JsonUtils.toJson(new JsonEntity<TokenEntity>("系统参数错误！"));
    }

    /**
     * 通过clientId 查询其公钥，并解析其token，
     * 如果token解析信息中 id和clientId符合，
     * 则说明客户端请求有效，在根据服务端编号，
     * 查询请求客户端是否具有该服务的权限，返回
     * 鉴权结果给服务
     * @param clientId 客户端编号
     * @param serverId 服务端编号
     * @param token
     * @return
     */
    @Override
    public String authToken(String clientId, String serverId, String token) {
        try {
            List<TSysOauthManage> list=domain.getAllByCode(clientId);
            if(null!=list&&list.size()>0){
                TSysOauthManage sysOauthManage=list.get(0);
                byte[] pri=RsaKeyHelper.generatePublicKey(sysOauthManage.getPassword());
                JWTInformation jwtInfo=JWTUtil.getInfoFromToken(token,pri);
                if(clientId.equals(jwtInfo.getId())){
                    return JsonUtils.toJson(new JsonEntity<TokenEntity>());
                }
            }
        } catch (IOException e) {
            return JsonUtils.toJson(new JsonEntity<TokenEntity>(e.getMessage()));
        } catch (NoSuchAlgorithmException e) {
            return JsonUtils.toJson(new JsonEntity<TokenEntity>(e.getMessage()));
        } catch (Exception e) {
            return JsonUtils.toJson(new JsonEntity<TokenEntity>(e.getMessage()));
        }
        return JsonUtils.toJson(new JsonEntity<TokenEntity>("系统参数错误！"));
    }
}
